from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from news import models, serializers
from rest_framework.pagination import PageNumberPagination
from django_filters import FilterSet
import django_filters


# Create your views here.


# 分页
class Fen(PageNumberPagination):
    page_size = 3
    page_size_query_param = "size"


# 排序
class Pai(FilterSet):
    read = django_filters.OrderingFilter(fields=['read'])

    class Meta:
        model = models.News
        fields = ['read']


#  展示新闻列表
class Xinlist(ModelViewSet):
    queryset = models.News.objects.all()
    serializer_class = serializers.SerNews
    pagination_class = Fen
    filterset_class = Pai


# 获取新闻详情
class NewXiang(APIView):
    def get(self, request):
        id = request.query_params.get("id")
        data = models.News.objects.filter(id=id).first()
        ser = serializers.SerNews(data)
        return Response({'msg': "ok", "data": ser.data})


# 获取当前新闻下的评论
class PingLun(APIView):
    def get(self, request):
        id = request.query_params.get("id")  # 获取的是新闻的id不是评论表的id
        data = models.Messgae.objects.filter(news=id)
        if data:
            ser = serializers.SerMessage(data,many=True)
            # userlist = models.User.objects.filter(id=ser.data.get("uname")).first()
            # userser = serializers.SerUser(userlist)
            return Response({"msg": "ok", "data": ser.data})
            # return Response({"msg": "ok", "data": ser.data})
        else:
            return Response({'msg': "no", "data": "该新闻暂无人评论"})


# 添加评论
class TianJia(APIView):
    def post(self, request):
        # new = request.data.get("new")
        # user = request.data.get("user")
        # message = request.data.get("message")
        data = serializers.SerMessage(data=request.data)
        if data.is_valid():
            data.save()
            return Response({"msg": "ok", "data": "评论成功"})
        else:
            return Response({"msg": data.errors})




# 用户登录
class Denglu(APIView):
    def get(self,request):
        name = request.query_params.get("name")
        psaaword = request.query_params.get("password")
        data = models.User.objects.filter(name=name,psaaword=psaaword).first()
        if data:
            ser = serializers.SerUser(data)
            return Response({"msg": "ok", "data": "登录成功","userid":ser.data.get("id")})
        else:
            data1 = models.User.objects.filter(name=name).first()
            if data1:
                return Response({"msg": "no", "data": "密码错误"})
            else:
                return Response({"msg": "no", "data": "该用户不是内部人员"})


# class Xinlist(APIView):
#     def get(self,request):
#         newslist = models.News.objects.all()
#         ser = serializers.SerNews(newslist,many=True)
#         return Response({"msg":"ok","data":ser.data})
